<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{path:'home'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="添加商品信息" type="info" show-icon center></el-alert>
      <el-steps align-center :active="stepActive - 0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab栏区域 -->
      <el-form
        :model="addForm"
        ref="addFormRef"
        label-position="top"
        label-width="100px"
        :rules="addFormRule"
      >
        <el-tabs
          @tab-click="tabClick"
          :before-leave="beforeLeave"
          :tab-position="'left'"
          v-model="stepActive"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="cateChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :key="item.attr_id" v-for="item in manyTabsData" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :key="index"
                  :label="element"
                  v-for="(element,index) in item.attr_vals"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :key="item.attr_id" v-for="item in onlyTabsData" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-dome"
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="reqHeader"
              :on-success="handleSuccess"
            >
              <el-button size="mini" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不能超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="addBtn" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog :close="closeImgDialog" title="图片预览" :visible.sync="isImgDialog" width="50%">
      <img :src="previewPath" />
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  data() {
    return {
      // 当前处于第几步
      stepActive: '0',
      cateList: [], // 分类列表数据
      // 添加商品数据
      addForm: {
        goods_name: '',
        goods_price: '',
        goods_number: '',
        goods_weight: '',
        goods_cat: [],
        pic: [],
        goods_introduce: '',
        attrs: []
      },
      previewPath: '',
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 动态参数列表
      manyTabsData: [],
      // 静态属性列表
      onlyTabsData: [],
      // 是否显示预览图片窗口
      isImgDialog: false,
      // 级联选择器设置
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 添加商品基本信息的校验规则
      addFormRule: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    cateChange() {},
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类数据失败')
      }
      this.cateList = res.data
      console.log(this.cateList)
    },
    // 切换tabs钩子函数   切换之前
    beforeLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && !this.cateID) {
        this.$message.error('请先选择分类')
        return false
      }
    },
    // 点击切换步骤
    tabClick() {
      if (this.stepActive === '1') {
        this.getParams('many')
      } else if (this.stepActive === '2') {
        this.getParams('only')
      }
    },
    closeImgDialog() {
      this.previewPath = ''
    },
    // 获取参数列表
    async getParams(sel) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateID}/attributes`,
        { params: { sel } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      if (sel === 'many') {
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.split(',')
        })
        this.manyTabsData = res.data
      } else if (sel === 'only') {
        this.onlyTabsData = res.data
      }
    },
    // 点击预览图片
    handlePreview(file) {
      this.previewPath = file.response.data.url
      this.isImgDialog = true
    },
    // 移除图片
    handleRemove(file, filelist) {
      const filepath = file.response.data.tmp_path
      const i = this.addForm.pic.findIndex(item => item === filepath)
      this.addForm.pic.splice(i, 1)
    },
    // 上传成功之后的回调函数
    handleSuccess(file) {
      if (file.meta.status !== 200) {
        return this.$message.error('上传失败')
      }
      this.addForm.pic.push(file.data.tmp_path)
      console.log(file)
    },
    // 点击按钮添加商品
    addGoods() {
      this.$refs.addFormRef.validate(valida => {
        console.log(valida)
        if (!valida) {
          return this.$message.error('请填写必要的表单项')
        }

        let from = _.cloneDeep(this.addForm)
        from.goods_cat = from.goods_cat.join(',')
        console.log(this.onlyTabsData, this.manyTabsData)
        this.onlyTabsData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          from.attrs.push(newInfo)
        })
        this.manyTabsData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(',')
          }
          from.attrs.push(newInfo)
        })
        this.Axios_addForm(from)
      })
    },
    async Axios_addForm(form) {
      const { data: res } = await this.$http.post('goods', form)
      if (res.meta.status !== 201) {
        return this.$message.error('添加失败')
      }
      this.$message.success('添加成功')
      this.$router.push('/goods')
    }
  },
  computed: {
    reqHeader() {
      return { Authorization: window.sessionStorage.getItem('token') }
    },
    cateID() {
      if (this.addForm.goods_cat.length !== 3) {
        return null
      }
      return this.addForm.goods_cat[2]
    }
  }
}
</script>
<style lang="less" scoped>
.el-steps {
  margin-top: 20px;
}
.el-tabs {
  margin-top: 20px;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.addBtn {
  margin-top: 15px;
}
</style>
